#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests


class AMapApi(object):

    def __init__(self):
        self.key = "596067041ac7b3c1af9dbba7d7d5acab"
        self.distance_api = "https://restapi.amap.com/v3/distance"
        self.traffic_api = "https://restapi.amap.com/v3/traffic/status/road"

    # https://restapi.amap.com/v3/distance?origins=116.481028,39.989643|114.481028,39.989643|115.481028,39.989643&destination=114.465302,40.004717&output=xml&key=<用户的key>
    def get_distance(self, start_point, end_point):
        """
        计算两点距离
        """
        params = dict(
            origins=start_point,
            destination=end_point,
            key=self.key
        )
        ret = requests.get(self.distance_api, params=params, timeout=3)
        # {'status': '1', 'info': 'OK', 'infocode': '10000', 'count': '1', 'results': [{'origin_id': '1', 'dest_id': '1', 'distance': '809', 'duration': '60'}]}
        try:
            data = ret.json()
            if data and data['info'] == 'OK' and data['results']:
                return data['results'][0]['distance']
        except Exception as e:
            print(e)
            return 0

    def get_traffic_status(self, name):
        params = dict(
            name=name,
            key=self.key,
            adcode=110000,
        )
        ret = requests.get(self.traffic_api, params=params, timeout=3)
        try:
            data = ret.json()
            if data and data['info'] == 'OK' and data['trafficinfo']:
                return data['trafficinfo']['evaluation']
        except Exception as e:
            print(e)
            return dict()





if __name__ == "__main__":
    print(AMapApi().get_distance("116.664053,39.531791", "116.671005,39.53664"))
        
